<?php
/**
 * 权限类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 16:16
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class Auth{
    /**
     * @var Request Request 实例
     */
    protected $_request;

    /**
     * @var mixed 权限开关 true/false
     */
    protected $_onoff;

    /**
     * @var object 实例
     */
    protected static $instance;

    /**
     * @var array 配置
     */
    protected $_config = array(
        'AUTH_ON'           => true,                     //认证开关
        'AUTH_TYPE'         => 1,                        //认证方式，1为实时认证；2为登录认证。
        'AUTH_GROUP'        => 'it_auth_group',          //用户组数据表名
        'AUTH_GROUP_ACCESS' => 'it_auth_group_access',   //用户组明细表
        'AUTH_RULE'         => 'it_auth_rule',           //权限规则表
        'AUTH_USER'         => 'it_admin'                //用户信息表
    );

    public function __construct(){
        $this->_request = Request::instance();
        $this->_onoff  = $this->_config['AUTH_ON'];
    }

    public function __set($name, $value){
        $this->$name = $value;
    }

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return Auth
     */
    public static function instance($options = []) {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 检查权限
     * @param string $name  需要验证的规则列表，支持逗号分隔的权限规则或索引数组
     * @param int $uid   认证用户的id
     * @param int $type
     * @param string $mode
     * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
     * @return bool  通过验证返回true;失败返回false
     */
    public function check($name, $uid, $type = 1, $mode = 'url', $relation = 'or'){
        if (!$this->_onoff) {   //未开启验证
            return true;
        }
        $authList = $this->getAuthList($uid, $type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存验证通过的规则名
        if ($mode == 'url') {
            $request = unserialize(strtolower(serialize($_REQUEST)));
        }
        foreach ($authList as $auth) {
            $query = preg_replace('/^.+\?/U', '', $auth);
            if ($mode == 'url' && $query != $auth) {
                parse_str($query, $param); //解析规则中的param
                $intersect = array_intersect_assoc($request, $param);
                $auth = preg_replace('/\?.*$/U', '', $auth);
                if (in_array($auth, $name) && $intersect == $param) {  //如果节点相符且url参数满足
                    $list[] = $auth;
                }
            } else if (in_array($auth, $name)) {
                $list[] = $auth;
            }
        }
        if ($relation == 'or' && !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation == 'and' && empty($diff)) {
            return true;
        }
        return false;
    }

    /**
     * 获取权限列表
     * @param int $uid  用户id
     * @param $type
     * @return array 权限列表
     */
    protected function getAuthList($uid, $type = 1){
        static $_authList = array(); //保存用户验证通过的权限列表
        $t = implode(',', (array)$type);
        if (isset($_authList[$uid . $t])) {
            return $_authList[$uid . $t];
        }
        if ($this->_config['AUTH_TYPE'] == 2 && isset($_SESSION['_AUTH_LIST_' . $uid . $t])) {
            return $_SESSION['_AUTH_LIST_' . $uid . $t];
        }
        $groups = $this->getGroups($uid);  //读取用户所属用户组
        $ids = array();
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['auth_ids'], ',')));
        }
        $ids = implode(',',array_unique($ids));  //保存用户所属用户组的权限规则id
        if (empty($ids)) {
            $_authList[$uid . $t] = array();
            return array();
        }
        $authList = $this->getAuth($ids,$type);  //读取用户组所有权限规则
        $_authList[$uid . $t] = $authList;
        if ($this->_config['AUTH_TYPE'] == 2) {
            $_SESSION['_AUTH_LIST_' . $uid . $t] = $authList;  //规则列表结果保存到session
        }
        return array_unique($authList);
    }

    /**
     * 获取用户所属用户组
     * @param int $uid  用户ID
     * @return mixed  用户所属的用户组信息
     */
    protected function getGroups($uid){
        static $groups = [];
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }
        $sql = "select a.uid,a.group_id,b.group_name,b.auth_ids from {$this->_config['AUTH_GROUP_ACCESS']} a left join {$this->_config['AUTH_GROUP']} b on a.group_id = b.id where a.uid = {$uid} and b.status = ".\Param::STATUS_ON;
        $user_groups = Db::query($sql);
        $groups[$uid] = $user_groups ?: array();
        return $groups[$uid];
    }

    /**
     * 读取用户组所有权限规则
     * @param $ids string 权限id
     * @param $type
     * @return array
     */
    protected function getAuth($ids, $type = 1){
        $sql = "select `auth_rule` from {$this->_config['AUTH_RULE']} where `id` in ($ids) and `type` = $type and `status` = ".\Param::STATUS_ON;
        $rules = Db::query($sql);
        $authList = array();
        foreach ($rules as $rule) {
            $authList[] = strtolower($rule['auth_rule']);
        }
        return $authList;
    }

    /**
     * 非ajax请求验证
     * @return string|\think\response\Json
     */
    public function jumpCheck(){
        $id = \think\Session::get('login');
        $session_end = \think\Session::get('session.end_time');  // 获取session结束时间
        if ( !$id || $session_end < time()) {
            \think\Session::delete('login');
            return error(-2, '登录过期！');
        }

        if ( $id == \Param::GROUP_ADMIN ) return success();  //超管不验证权限、状态

        $info = \think\Db::name('admin')->where(['id'=>$id,'status'=>\Param::STATUS_ON])->find();
        if ( !$info ) {
            \think\Session::delete('login');
            return error(-2, '抱歉，您已被禁用！');
        }

        $params = $this->_request->post('rule');
        preg_match('/^\/\w+\/\w+\/\w+/',strtolower($params), $rule);
        if ( in_array($rule[0], ['/admin/admin/setpassword']) ) {
            $this->_onoff  = false;  // 关闭权限验证
        }
        if ( !$this->check($rule[0], $id) ) return error(-1, '抱歉，您不具备该权限!');
        return success();
    }
}